<?php

namespace app\api\controller\ai;

use thinkct\controller\Frontend;
use ba\PayLib;
use think\facade\Db;
use think\facade\Config;
use epay\CodePay;
use epay\Epay;

class Pay extends Frontend
{
    protected array $noNeedLogin = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function payment()
    {
        //try {
            $money = $this->request->post('money', 1);
            $type = $this->request->post('type', 'alipay');
            $title = '余额充值';
            $sn = date('YmdHis') . mt_rand(100000, 999999);

            if (!cache()->get('sys_auth')) $this->error('免费版不支持在线充值');

            if ($money < 1) {
                $this->error('充值金额不能小于1元');
            }
            // 写入数据库
            $payment = [
                'user_id' => $this->auth->id ?? 1,
                'title' => $title,
                'amount' => $money,
                'type' => $type,
                'sn' => $sn,
                'create_time' => time(),
            ];
            Db::name('payment')->insert($payment);


            ### 易支付操作开始 ###
            $ePayType = Config::get('pay.ePay.type');
            if (str_contains($ePayType, $type)) {
                $ePay_config = [
                    'url' => Config::get('pay.ePay.url'),
                    'pid' => Config::get('pay.ePay.pid'),
                    'key' => Config::get('pay.ePay.key'),
                    'notify_url' => $this->request->domain() . '/api/ai.pay/return_epay',
                    'return_url' => $this->request->domain() . '/api/ai.pay/return_epay',
                ];
                $ePay = new Epay($ePay_config);
                $data = [
                    'type' => $type,
                    'out_trade_no' => $sn,
                    'name' => $title,
                    'money' => $money,
                ];
                $result = $ePay->submitOrder($data);
                if ($result['code'] == 1) {
                    $payurl = $result['qrcode'] ?? $result['payurl'];
                    $this->success('请支付', [
                        'title' => $title,
                        'sn' => $sn,
                        'money' => $money,
                        'type' => $type, // 支付方式
                        'code_url' => 'https://api.uomg.com/api/qrcode?url=' . urlencode($payurl),
                        'code_type' => 'qrCode',
                    ]);
                } else {
                    $this->error($result['msg']);
                }
            }
            ### 易支付操作开始 ###



            ### 码支付操作开始 ###
            $codePayType = Config::get('pay.codePay.type');
            // 判断是否存在 'alipay,wechat'
            if (str_contains($codePayType, $type)) {
                $codepay_config = [
                    'url' => Config::get('pay.codePay.url'),
                    'pid' => Config::get('pay.codePay.pid'),
                    'key' => Config::get('pay.codePay.key'),
                    'notify_url' => $this->request->domain() . '/api/ai.pay/return_codepay',
                    'return_url' => $this->request->domain() . '/api/ai.pay/return_codepay',
                ];
                $codepay = new CodePay($codepay_config);
                $data = [
                    'type' => $type,
                    'out_trade_no' => $sn,
                    'name' => $title,
                    'money' => $money,
                ];

                $result = $codepay->submitOrder($data);
                if ($result['code'] == 200) {
                    $this->success('请支付', [
                        'title' => $title,
                        'sn' => $sn,
                        'money' => $money,
                        'type' => $type, // 支付方式
                        'code_url' => $result['code_url'],
                        'code_type' => 'qrCode',
                    ]);
                } else {
                    $this->error($result['msg']);
                }
            }
            ### 码支付操作结束 ###




            ### 官方支付操作开始 ###
            $code_url = '';
            $config = PayLib::getConfig();
            // 微信
            if ($type == 'wechat') {
//            $code_url = '1';
                $order = [
                    'out_trade_no' => $sn,
                    'total_fee' => $money * 100,
                    'body' => $title,
                ];
                $config['wechat']['default']['notify_url'] = $this->request->domain() . '/api/ai.pay/notify';
                $config['wechat']['default']['return_url'] = $this->request->domain() . '/api/ai.pay/return';
                $res = \Yansongda\Pay\Pay::wechat($config)->scan($order);
                $code_url = $res->code_url;
            }

            // 支付宝
            if ($type == 'alipay') {
                $order = [
                    'out_trade_no' => $sn,
                    'total_amount' => $money,
                    'subject' => $title,
                    'qr_pay_mode' => '4',
                    'qrcode_width' => 220,
                ];
                $config['alipay']['default']['notify_url'] = $this->request->domain() . '/api/ai.pay/notify';
                $config['alipay']['default']['return_url'] = $this->request->domain() . '/api/ai.pay/return';
                //die(var_dump($config));
                $res = \Yansongda\Pay\Pay::alipay($config)->web($order);
                //return $res->getBody()->getContents();
                $code_url = $res->getBody()->getContents();
            }

            $this->success('请支付', [
                'title' => $title,
                'sn' => $sn,
                'money' => $money,
                'type' => $type, // 支付方式
                'code_url' => $code_url,
                'code_type' => 'iframe',
            ]);
            ### 官方支付操作结束 ###
//        } catch (\Exception $e) {
//            $this->error('暂无可用支付方式');
//        }
    }

    // 查询订单
    public function query(): void
    {
        $sn = $this->request->get('sn');
        $payment = Db::name('payment')->where(['sn' => $sn])->find();
        if ($payment) {
            if ($payment['status'] == 'success') {
                $this->success('支付成功',[
                    'status' => 'success',
                    'pay_time' => $payment['pay_time'],
                ]);
            } else {
                $this->error('等待支付');
            }

        } else {
            $this->error('查询失败');
        }
    }

    public function return()
    {
        try {
            $result = \Yansongda\Pay\Pay::alipay(PayLib::getConfig())->callback();

            $out_trade_no = $result['out_trade_no'] ?? '';
            // 查询数据
            $payment = Db::name('payment')->where(['sn' => $out_trade_no, 'status' => 'wait'])->find();
            if ($payment) {
                Db::name('payment')->where(['sn' => $out_trade_no])->update(['status' => 'success', 'pay_time' => time()]);

                if ($result['total_amount'] == $payment['amount']) {
                    // 更新用户余额
                    $user = \app\common\model\User::where('id', $payment['user_id'])->find();
                    $user->money = $user->money + $payment['amount'];
                    $user->save();
                    // 写入余额变动记录
                    \app\common\model\UserMoneyLog::create([
                        'user_id' => $payment['user_id'],
                        'money' => $payment['amount'],
                        'before' => $user->money - $payment['amount'],
                        'after' => $user->money,
                        'memo' => '充值' . $payment['amount'] . '元',
                    ]);
                }
                return '支付成功';
            }
        } catch (Throwable $e) {
            return '支付失败';
        }
    }

    public function notify()
    {
        return '';
    }


    public function return_epay(): string
    {
        $epay_config = [
            'pid' => Config::get('pay.ePay.pid'),
            'key' => Config::get('pay.ePay.key'),
        ];
        $ePay = new Epay($epay_config);
        $result = $ePay->verify();
        if ($result) {
            $out_trade_no = $this->request->get('out_trade_no');
            $money = $this->request->get('money');
            $payment = Db::name('payment')->where(['sn' => $out_trade_no, 'status' => 'wait'])->find();
            if ($payment) {
                Db::name('payment')->where(['sn' => $out_trade_no])->update(['status' => 'success', 'pay_time' => time()]);

                if ($money == $payment['amount']) {
                    // 更新用户余额
                    $user = \app\common\model\User::where('id', $payment['user_id'])->find();
                    $user->money = $user->money + $payment['amount'];
                    $user->save();
                    // 写入余额变动记录
                    \app\common\model\UserMoneyLog::create([
                        'user_id' => $payment['user_id'],
                        'money' => $payment['amount'],
                        'before' => $user->money - $payment['amount'],
                        'after' => $user->money,
                        'memo' => '充值' . $payment['amount'] . '元',
                    ]);
                }
            }
            return 'success';
        }

        return 'fail';
    }

    public function return_codepay(): string
    {
        $codepay_config = [
            'pid' => Config::get('pay.codePay.pid'),
            'key' => Config::get('pay.codePay.key'),
        ];
        $codepay = new CodePay($codepay_config);
        $result = $codepay->verify();
        if ($result) {
            $out_trade_no = $this->request->get('out_trade_no');
            $money = $this->request->get('money');
            $payment = Db::name('payment')->where(['sn' => $out_trade_no, 'status' => 'wait'])->find();
            if ($payment) {
                Db::name('payment')->where(['sn' => $out_trade_no])->update(['status' => 'success', 'pay_time' => time()]);

                if ($money == $payment['amount']) {
                    // 更新用户余额
                    $user = \app\common\model\User::where('id', $payment['user_id'])->find();
                    $user->money = $user->money + $payment['amount'];
                    $user->save();
                    // 写入余额变动记录
                    \app\common\model\UserMoneyLog::create([
                        'user_id' => $payment['user_id'],
                        'money' => $payment['amount'],
                        'before' => $user->money - $payment['amount'],
                        'after' => $user->money,
                        'memo' => '充值' . $payment['amount'] . '元',
                    ]);
                }
            }
            return 'success';
        }

        return 'fail';
    }
}